package com.bwie.goods.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bwie.goods.util.JwtUtil;
import com.bwie.miaosha.common.utils.PageUtils;
import com.bwie.miaosha.common.utils.R;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.bwie.goods.entity.UserEntity;
import com.bwie.goods.service.UserService;




/**
 * 
 *
 * @author HouDing
 * @email 1398853436@qq.com
 * @date 2022-02-22 19:41:40
 */
@RestController
@RequestMapping("goods/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtUtil jwtUtil;
    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = userService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id){
		UserEntity user = userService.getById(id);

        return R.ok().put("user", user);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody UserEntity user){
		userService.save(user);

        return R.ok();
    }
    //登录
    @RequestMapping("/login")
    public R login(@RequestBody UserEntity user){
		UserEntity userEntity = userService.login(user);
        if (userEntity!=null) {
            Date date = new Date();
            userEntity.setLastLoginData(date);
            userEntity.setLoginCount(userEntity.getLoginCount()+1);

            String token = jwtUtil.createJWT(user.getId() + "", user.getNickname(), "user");
            userService.updateById(userEntity);
            return R.ok().put("token",token).put("user",userEntity);
        }
        return R.error("手机号或密码错误");
    }
    //注册
    @RequestMapping("/register")
    public R register(@RequestBody UserEntity user){
        QueryWrapper<UserEntity> nickname = new QueryWrapper<UserEntity>().eq("nickname", user.getNickname());
        UserEntity one = userService.getOne(nickname);
        if (one!=null) {
            return R.error(1,"该用户已存在，请勿再次注册！");
        }
        userService.register(user);
        return R.ok();
    }



    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody UserEntity user){
		userService.updateById(user);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] ids){
		userService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

}
